#include "udpclient.h"
#include "ui_udpclient.h"
#include <QTextCodec>
#include <QDebug>
UdpClient::UdpClient(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::UdpClient)
{
    ui->setupUi(this);
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
    clientudp=new QUdpSocket(this);
    clientudp->bind(6000,QUdpSocket::ShareAddress);//绑定读数据端口(监听端口)，允许其他服务绑定到此端口
    connect(clientudp,SIGNAL(readyRead()),this,SLOT(recv()));
}

UdpClient::~UdpClient()
{
    delete ui;
}

void UdpClient::on_pushButton_clicked()
{
//    QHostAddress serverip;
//    serverip.setAddress(QString("192.168.0.7"));//这是人为指定ip地址的方法
    clientudp->writeDatagram(QVariant(ui->textEdit_write->toPlainText()).toByteArray(),QHostAddress::LocalHost,5000);//向5000端口写数据
}
void UdpClient::recv()
{
    while(clientudp->hasPendingDatagrams())
    {
        QByteArray data;
        data.resize(clientudp->pendingDatagramSize());
        clientudp->readDatagram(data.data(),data.size());
        ui->textEdit_show->setText(QVariant(data).toString());
    }
}
//注意，监听与发送的端口可以相同也可以不同，它们相对独立，就像有名管道
